package GameServer

import (
	. "SGNet"
	log "misc/seelog"
	"time"
)

const (
	MODULE_SREVER = 0
	MODULE_HAll   = 1
)

type IModule interface {
	OnLoad()
	AddMessage(*Message)
}

type ModuleInfo struct {
	InMessageQueue  chan *Message
	messageHandlers map[uint16]ServerHandlerFunc
	commandandlers  map[uint16]ServerHandlerFunc
}

func (this *ModuleInfo) New() {
	this.messageHandlers = make(map[uint16]ServerHandlerFunc)
	this.commandandlers = make(map[uint16]ServerHandlerFunc)
	this.InMessageQueue = make(chan *Message, SERVERQUEUE_SIZE)
}
func (this *ModuleInfo) Run() {
	go this.loop()
}
func (this *ModuleInfo) loop() {
	ticker := time.Tick(time.Millisecond)
	for _ = range ticker {
		this.processMessage()
	}
}
func (this *ModuleInfo) processMessage() {
	count := len(this.InMessageQueue)
	for i := 0; i < count; i++ {
		command := <-this.InMessageQueue
		if command.Type == MESSAGETYPE_CLIENT {
			if fn, ok := this.messageHandlers[command.Id]; ok {
				fn(command)
			} else {
				log.Info("收到了不存在的消息包", command.Id)
			}
		} else if command.Type == MESSAGETYPE_CMD {
			if fn, ok := this.commandandlers[command.Id]; ok {
				fn(command)
			} else {
				log.Info("收到了不存在的消息包", command.Id)
			}
		}
	}
}

func (this *ModuleInfo) AddHandler(id uint16, fn ServerHandlerFunc) {
	this.messageHandlers[id] = fn
}

func (this *ModuleInfo) AddCommandHandler(id uint16, fn ServerHandlerFunc) {
	this.commandandlers[id] = fn
}
func (this *ModuleInfo) AddMessage(msg *Message) {
	this.InMessageQueue <- msg
}

var moduleMap map[int]IModule

func RunServer() {
	initID2Module()
	initDispatcher()
	moduleMap = make(map[int]IModule)
	moduleMap[0] = NewGameServer()
	moduleMap[1] = NewGameHall()
	for _, m := range moduleMap {
		m.OnLoad()
	}
}

func GetGameHall() *GameHall {
	return moduleMap[MODULE_HAll].(*GameHall)
}

func GetGameServer() *GameServer {
	return moduleMap[MODULE_SREVER].(*GameServer)
}
